<?php
defined('_JEXEC') or die('Restricted access');
$img_path = JURI::root(true).'/images/fileupload/';
$cache_dir = JPATH_COMPONENT.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
$cache_filename = $cache_dir."linhkien.php";
if(JFile::exists($cache_filename))
{
	include($cache_filename);
	$cache_data = $cache_linhkien;
}else $cache_data = array();

?>

<div class='tab_content' id="tab_list_engine">
	<div class='container-fluid margin10'>
		<div class='row-fluid'>
			<div class='widget widget-padding span12'>
				<div class='widget-header'>
					<i class="icon-list-alt"></i>
					<h5><?php echo JText::_('COM_KETNOI_LISTENGINE') ?></h5>
				</div>
				<div class='widget-body'>
					<div class='row-fluid'>
						<div class='span12'>
							<?php if(Utility::checkAccess("core.create", $this->canDo)): ?>
								<a class='btn btn-primary' href='#create_engine'>
									<i class='icon-plus icon-white'></i>
									<?php echo JText::_("COM_KETNOI_CREATEBTN") ?>
								</a>
							<?php endif; ?>
							<?php if(Utility::isAdmin()): ?>
							<a onclick="showModalPermission('engine')" class='btn btn-danger'>
								<i class='icon-lock icon-white'></i>
								Phân quyền
							</a>
							<?php endif; ?>
						</div>
					
					</div>
					
					<div class="row-fluid">
						<div class='span12'>
							<div id='grid_engine' class='margin10'></div>
						</div>
					</div>
					
				</div>
				
			</div>
		</div>
	</div>
</div>
<script>
    jQuery(document).ready(function(){    
        jQuery("#grid_engine").kendoGrid({
			dataSource: {
				transport: {
					read:{
						url:"index.php?option=com_ketnoi&view=engine&tmpl=component",
						dataType:"json"
					}	
				},
				schema: {
					data:"results",
					total:"total",
					model: {
                        fields: {
							sodungluongbaohanh: { type: "number" }
                        }
                    }
				},
				pageSize: 10,
				serverPaging: true
			},
			pageable:{
				pageSizes: true,
				messages: {
					display: "{0} - {1} <?php echo JText::_('COM_KETNOI_MESSAGEOF') ?> {2} <?php echo JText::_('COM_KETNOI_MESSAGEDATA') ?>",
					empty: "",
					page: "Page",
					of: "of {0}",
					itemsPerPage: "<?php echo JText::_('COM_KETNOI_MESSAGEITEMPERPAGE') ?>",
					first: "<?php echo JText::_('COM_KETNOI_GOTOFIRSTPAGE') ?>",
					previous: "<?php echo JText::_('COM_KETNOI_GOTOPREVIOUSPAGE') ?>",
					next: "<?php echo JText::_('COM_KETNOI_GOTONEXTPAGE') ?>",
					last: "<?php echo JText::_('COM_KETNOI_GOTOLASTPAGE') ?>",
					refresh: "Refresh"	
				}
			},
			scrollable:false,
			autoBind: false,
			detailTemplate: kendo.template($("#template").html()),
			detailInit: detailInit,
			columns: [
                {
					field:"ma",
					title:"<?php echo JText::_('COM_KETNOI_CODE') ?>",
					template:"<a onclick='edit_hash_engine(${id})'>${ma}</a>"
				},
				{
					field:"ten",
					title:"<?php echo JText::_('COM_KETNOI_ENGINENAME') ?>"
				},
				{
					field:"sothangbaohanh",
					title:"<?php echo JText::_('COM_KETNOI_ENGINE_SOTHANG') ?>"
				},
				{
					field:"sodungluongbaohanh",
					title:"<?php echo JText::_('COM_KETNOI_ENGINE_SODUNGLUONG') ?>",
					format:"{0:n0}"
				},
				{
					field:"tendonvi",
					title:"<?php echo JText::_('COM_KETNOI_DONVITINH') ?>"
				},
				{
					title:"",
					template:kendo.template($("#action_tpl").html()),
					width:100
				}
            ],
            dataBound:function(){
				if(this._data.length == 0)
				{
					var colspan = jQuery("#grid_engine").find('table thead tr th').length;
                    jQuery("#grid_engine").find('table tbody').append("<tr><td colspan='"+colspan+"'><?php echo JText::_('COM_KETNOI_EMPTYDATA') ?></td></tr>");
				}

				//make column on reponsive
				AddCellLabel("grid_engine");	
            }
		});
    })
	var cache_data = [];
    function detailInit(e) {
    	var detailRow = e.detailRow;

        	detailRow.find(".tabstrip").kendoTabStrip({
            	animation: {
            		sopen: { effects: "fadeIn" }
            	}
           }); 

        	detailRow.find(".engine_linhkien_form").validate({  
        		errorPlacement: function(error, element) {
        			if($(element).hasClass("error"))
        			{
        				hideLoader($('#tab_list_engine'));
        			}
                    error.remove();          
                },
                onkeyup:false,
                onfocusout:false,
                rules:{
                    ma:{
                        required:true,
                        remote:{
                			url:"index.php?option=com_ketnoi&task=linhkien.checkMaLinhkien&tmpl=raw",
                			data:{
                				ma:function(value){       	
                					return detailRow.find(".engine_linhkien_form input[name='ma']").val();
                				}
                			},
                			beforeSend:function(){
                				showLoader($('#tab_list_engine'));
                			}
                		}
                    }
                },
                messages:{
                	ma:{
                        required:'Vui lòng nhập mã linh kiện', 
                        remote:'Mã linh kiện không tồn tại'
                    }
                }
            })
            
            detailRow.find(".engine_linhkien_form").ajaxForm({
            	beforeSubmit:function(){   		
            		showLoader($('#tab_list_engine'));
            	},
            	success:function(response){
            		var obj = checkJSON(response);
            		if(obj.is_json)
            		{
            			if(!obj.result.success)
                		{
                			var error = obj.result.error;
                			alertify.alert(error);
                		}else
                		{
                			var dataSource = detailRow.find(".grid_linhkien_nested").data("kendoGrid").dataSource;
            				dataSource.read();
                    	}	
            		}
            		
            		hideLoader($('#tab_list_engine'));
            	}
            });

        	detailRow.find(".linhkien_select").chosentable({
        		max_selected_options:1,
        		search_contains: true,
        		no_results_text: 'Không tìm thấy:',
        		template: function (text, templateData) {
        	    	return [
        	      		"<div class='k-grid-content'><table><tbody><tr><td>" + templateData.ma + "</td>",
        	      		"<td>" + templateData.ten + "</td></tr></tbody></table>",      
        	    	].join("");
        	  	},
        	  	headerTemplate:'<div class="k-grid-header"><div class="k-grid-header-wrap"> <table style="width:100%"><thead><tr><th class="k-header" style="width:50%">Mã linh kiện</th><th class="k-header" >Tên linh kiện</th></tr></thead></table></div></div>'
        	});
			
        	var grid = detailRow.find(".grid_linhkien_nested").kendoGrid({
        		dataSource: {
					transport: {
						read:{
							url:"index.php?option=com_ketnoi&view=linhkien&tmpl=raw",
							dataType:"json"
						}	
					},
					schema: {
						data:"results",
						total:"total",
						model: {
	                        fields: {
								sodungluongbaohanh: { type: "number" }
	                        }
	                    }
					},
					serverPaging: true,
					serverFiltering: true,
	                pageSize:5,
	                filter: { field: "el.engine_id", operator: "eq", value: e.data.id }
				},
				pageable:{
					pageSizes: true,
					messages: {
						display: "{0} - {1} <?php echo JText::_('COM_KETNOI_MESSAGEOF') ?> {2} <?php echo JText::_('COM_KETNOI_MESSAGEDATA') ?>",
						empty: "",
						page: "Page",
						of: "of {0}",
						itemsPerPage: "<?php echo JText::_('COM_KETNOI_MESSAGEITEMPERPAGE') ?>",
						first: "<?php echo JText::_('COM_KETNOI_GOTOFIRSTPAGE') ?>",
						previous: "<?php echo JText::_('COM_KETNOI_GOTOPREVIOUSPAGE') ?>",
						next: "<?php echo JText::_('COM_KETNOI_GOTONEXTPAGE') ?>",
						last: "<?php echo JText::_('COM_KETNOI_GOTOLASTPAGE') ?>",
						refresh: "Refresh"	
					}
				},
				scrollable:false,
				
				columns: [
	                {
						field:"ma",
						title:"<?php echo JText::_('COM_KETNOI_CODE') ?>"
					},
					{
						field:"ten",
						title:"Tên linh kiện"
					},
					{
						field:"sothangbaohanh",
						title:"<?php echo JText::_('COM_KETNOI_ENGINE_SOTHANG') ?>"
					},
					{
						field:"sodungluongbaohanh",
						title:"<?php echo JText::_('COM_KETNOI_ENGINE_SODUNGLUONG') ?>",
						format:"{0:n0}"
						
					},
					{
						field:"tendonvi",
						title:"<?php echo JText::_('COM_KETNOI_DONVITINH') ?>"
					}
	            ],
	            dataBound:function(){
					if(this._data.length == 0)
					{
						var colspan = detailRow.find(".grid_linhkien_nested").find('table thead tr th').length;
						detailRow.find(".grid_linhkien_nested").find('table tbody').append("<tr><td colspan='"+colspan+"'><?php echo JText::_('COM_KETNOI_EMPTYDATA') ?></td></tr>");
					}	
					//make column on reponsive
					//AddCellLabel("grid_linhkien_nested");	
	            }
        	});             
	}
	
</script>

<script type="text/x-kendo-template" id="template">
	<div class="tabstrip">
		<ul>
			
            <li class="k-state-active" grid='.grid_linhkien_nested'>
                Linh kiện máy #= ten #
            </li>
			<li >
				Thông tin máy
            </li>
        </ul>
        
        <div>
			<div style="padding:10px">
			<div class="row-fluid">
				<form method="post" class='engine_linhkien_form'>
				<div class="span6">
					<div class="chosen_multiple chosen_table chosen_quickcreate">
					    <select data-placeholder="Mã linh kiện" class="linhkien_select" multiple name="linhkien_id">
					    	<?php foreach ($cache_data as $linhkien): ?>
					        	<option value="<?php echo $linhkien["id"] ?>" data-ten="<?php echo $linhkien["ten"] ?>" data-ma="<?php echo $linhkien["ma"] ?>">
					            	<?php echo $linhkien["ma"] ?> - <?php echo $linhkien["ten"] ?> 
					            </option>
					        <?php endforeach; ?>
					    </select>
						<a class='btn btn-info fix-btn' onclick='showModalCreateLinhkien_popup(this)'>
							<i class='icon icon-plus'></i>
						</a>
					</div>
					<input type="hidden" name="option" value="com_ketnoi" />
					<input type="hidden" name="task" value="engine.save_engine_linhkien" />
					<input type="hidden" name="tmpl" value="raw" />
					<input type="hidden" name="engine_id" value="#= data.id #" />
				</div>
				<div class="span6">
					<button class="btn" type="submit">Thêm</button>
				</div>
				</form>
				<br><br>
			</div>
       		<div class="grid_linhkien_nested"></div>
			</div>
        </div>

		<div>
       		<div class="row-fluid">
				<div class='span12'>
					<div class="control-group">
				    	<label class="control-label detailgrid">
				        	Hình ảnh:								
						</label>
					    <div class="controls row-fluid">
							<div id="fileList">
					    	#
								var arr = JSON.parse(hinhanh);
								for(var i = 0;i < arr.length ; i++)
								{
									var img = arr[i];
							#
									
									<div>
										<img class="img-polaroid" src="<?= $img_path ?>#= img #" height="60">
										<img style="display: none;" class="img_tmp" src="<?= $img_path ?>#= img #" height="60">
									</div>
							#
								} 
							# 	 
							</div>          	
					    </div>
				    </div>
				</div>
			</div>

			<div class="row-fluid">
				<div class='span12'>
					<div class="control-group">
				    	<label class="control-label detailgrid">
				        	Ghi chú:								
						</label>
					    <div class="controls row-fluid">
							<span class="detail_grid_info">#= ghichu #</span>          	
					    </div>
				    </div>
				</div>
			</div>
        </div>
	</div>

</script>

<script type="text/x-kendo-template" id="action_tpl">
	<div class="btn-group">
		<?php if(Utility::checkAccess("core.edit", $this->canDo)): ?>
  		<a onclick="edit_hash_engine(#= data.id #)" class="btn btn-info">
			<i class='icon-edit icon-large'></i>
			Sửa
		</a>
		<?php endif; ?>
		<?php if(Utility::checkAccess("core.delete", $this->canDo)): ?>
  		<a onclick="deleteEngine(#= data.id #)" class="btn btn-info">
			<i class='icon-trash icon-large'></i>
			Xóa
		</a>
		<?php endif; ?>
	</div>
</script>